package com.ztf0337.mycurriculumdesign.ui.manager;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import com.ztf0337.mycurriculumdesign.service.ParkLotService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MUpdateParkLotActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PICK_IMAGE = 1001;
    private static final int REQUEST_CODE_PERMISSION = 1002;
    private ImageView uploadImage;
    private Uri selectedImageUri;
    private ParkLotService parkLotService;
    private int FROM = 0;

    private Long parkLotId = -1L;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.m_activity_input_park_lot);
        parkLotService = new ParkLotService(this);

        Intent intent = getIntent();
        FROM = intent.getIntExtra("from",0);

        ImageView btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> {
            finish();
        });

        uploadImage = findViewById(R.id.imageView);
        uploadImage.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_PERMISSION);
            } else {
                openGallery();
            }
        });


        EditText et_park_lot_name,et_local,et_type,et_information,et_phone;
        Switch switch_status;
        et_park_lot_name = findViewById(R.id.et_park_lot_name);
        et_local = findViewById(R.id.et_local);
        et_type = findViewById(R.id.et_type);
        et_information = findViewById(R.id.et_information);
        et_phone = findViewById(R.id.et_phone);
        switch_status = findViewById(R.id.switch_status);
        Button btn_submit = findViewById(R.id.btn_submit);



        if (FROM == 2) {
            long id = intent.getLongExtra("id",-1L);
            if (id == -1L) {
                Toast.makeText(this, "系统错误", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            ParkLot parkLotById = parkLotService.getParkLotById(id);
            et_park_lot_name.setText(parkLotById.getParkLotName());
            et_local.setText(parkLotById.getLocal());
            et_type.setText(parkLotById.getType());
            et_information.setText(parkLotById.getInformation());
            et_phone.setText(parkLotById.getPhone());
            switch_status.setChecked(parkLotById.getStatus());
            File filesDir = this.getFilesDir();
            File imagesDir = new File(filesDir, "gate_images");
            String child = parkLotById.getUrl();
            Log.d("文件测试", "获取到图片"+child);
            File targetImage = new File(imagesDir, child);
            if (targetImage.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(targetImage.getAbsolutePath());
                uploadImage.setImageBitmap(bitmap);
            } else {
                uploadImage.setImageResource(R.drawable.img_default_park_lot);
            }

            btn_submit.setOnClickListener(v -> {
                String park_lot_name,local,type,information,phone;
                boolean status;
                park_lot_name = et_park_lot_name.getText().toString().trim();
                local = et_local.getText().toString().trim();
                type = et_type.getText().toString().trim();
                information = et_information.getText().toString().trim();
                phone = et_phone.getText().toString().trim();
                status = switch_status.isChecked();

                String s = null;
                if (selectedImageUri != null) {
                    s = saveImageToInternalStorage(selectedImageUri);
                }
                parkLotById.setParkLotName(park_lot_name);
                parkLotById.setLocal(local);
                parkLotById.setType(type);
                parkLotById.setInformation(information);
                parkLotById.setPhone(phone);
                parkLotById.setStatus(status);
                if (s != null) {
                    parkLotById.setUrl(s);
                }
                if (parkLotById.getParkLotName().length()<10
                        && parkLotById.getInformation().length() <20
                        && parkLotById.getLocal().length()<20
                        && parkLotById.getPhone().length()< 20
                        && parkLotById.getType().length() < 10) {
                    parkLotService.update(parkLotById);
                    Toast.makeText(this, "更改成功", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(this, MParkLotDetailActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.putExtra("id", parkLotById.getId());
                    this.startActivity(i);
                } else {
                    Toast.makeText(this, "输入的信息过长", Toast.LENGTH_SHORT).show();
                }
                finish();
            });
        }
        if (FROM == 1) {
            btn_submit.setOnClickListener(v -> {
                String park_lot_name,local,type,information,phone;
                boolean status;
                park_lot_name = et_park_lot_name.getText().toString().trim();
                local = et_local.getText().toString().trim();
                type = et_type.getText().toString().trim();
                information = et_information.getText().toString().trim();
                phone = et_phone.getText().toString().trim();
                status = switch_status.isChecked();

                String s = null;
                if (selectedImageUri != null) {
                    s = saveImageToInternalStorage(selectedImageUri);
                }

                ParkLot parkLot = new ParkLot();
                parkLot.setParkLotName(park_lot_name);
                parkLot.setLocal(local);
                parkLot.setType(type);
                parkLot.setInformation(information);
                parkLot.setPhone(phone);
                parkLot.setStatus(status);
                parkLot.setTotalSpaces(0);
                parkLot.setAvailableSpaces(0);
                if (s != null) {
                    parkLot.setUrl(s);
                } else {
                    parkLot.setUrl("null");
                }
                parkLotService.inset(parkLot);
                Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(this,ManagerHomeActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra("open",1);
                this.startActivity(i);
                finish();
            });

        }

    }

    // 打开相册
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    // 权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery();
            } else {
                Toast.makeText(this, "请授予访问存储权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 接收选中的图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                uploadImage.setImageURI(selectedImageUri);
            }
        }
    }

    public String getFileExtensionFromUri(Context context, Uri uri) {
        String extension = null;

        if (uri.getScheme().equals("content")) {
            Cursor cursor = context.getContentResolver().query(
                    uri, null, null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        if (nameIndex >= 0) {
                            String fileName = cursor.getString(nameIndex);
                            extension = getExtensionFromFileName(fileName);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }

        if (extension == null && uri.getScheme().equals("file")) {
            String fileName = uri.getLastPathSegment();
            extension = getExtensionFromFileName(fileName);
        }

        return extension;
    }

    private String getExtensionFromFileName(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return null;
    }


    private String saveImageToInternalStorage(Uri sourceUri) {
        File filesDir = getFilesDir();
        File imagesDir = new File(filesDir, "gate_images");

        if (!imagesDir.exists()) {
            boolean created = imagesDir.mkdirs();
            if (!created) {
                Log.e("SaveImage", "Failed to create images directory");
                return null;
            }
        }

        String type = getFileExtensionFromUri(this, sourceUri);
        String fileName = "IMG_" + System.currentTimeMillis() + type;
        File targetFile = new File(imagesDir, fileName);

        try (
                InputStream in = getContentResolver().openInputStream(sourceUri);
                OutputStream out = new FileOutputStream(targetFile)
        ) {
            if (in != null) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                Log.d("SaveImage", "Saved to: " + targetFile.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;

    }




}
